package com.dianjing.dianqun.common.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.dianjing.dianqun.common.ResponseData;
import com.dianjing.dianqun.common.base.BaseRestController;

/**
 * @date : 2017年11月28日
 * 
 * @author: baoyongtao
 * 
 * @see :
 * 
 */
@ControllerAdvice
public class GlobalExceptionHandler extends BaseRestController{
	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 系统异常处理 只处理 404 400 403 异常
	 * 
	 * @param req
	 * @param resp
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = Exception.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e,HttpServletResponse response) throws Exception {
		logger.error("found exception : " +e.getClass().getName());
		if (request.getHeader("accept").contains("application/json")  || (request.getHeader("X-Requested-With")!= null && request
				.getHeader("X-Requested-With").contains("XMLHttpRequest") || request.getRequestURI().startsWith("/api/"))) {
			ResponseData r = new ResponseData();
			r.setMessage(e.getMessage());
			if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
				r.setData("No Handler Found Exception");
			}else if(e instanceof org.springframework.web.bind.MissingServletRequestParameterException) {
				r.setData("Parameter bind Exception");
			}else if(e instanceof org.apache.shiro.authz.UnauthorizedException) {
				r.setData("Unable to handle Requests");
			}else {
				throw e;
			}
			r.setCode(ResponseData.STATUS_ERROR);
			renderString(response, r);
			return null;
		}
		return new ModelAndView("404");
	}
}